package com.easy.service.impl;

import com.easy.bean.CommentBean;
import com.easy.bean.GiveBean;
import com.easy.bean.PostBean;
import com.easy.mapper.CommentDao;
import com.easy.service.CommentService;
import com.easy.service.MessageService;
import com.easy.service.PostService;
import com.easy.util.LogMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
//@Transactional
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentDao commentDao;
    @Autowired
    private PostService postService;
    @Autowired
    private MessageService messageService;

    @Override
    @Transactional
    @LogMethod(serviceName = "发表评论",recordReturn = true)
    public CommentBean add(CommentBean comment) {
        // 参数校验
        if (comment.getPostId() == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }
        if (comment.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (comment.getCommentContent() == null || comment.getCommentContent().trim().isEmpty()) {
            throw new IllegalArgumentException("评论内容不能为空");
        }

        // 设置默认值
        comment.setComCreatetime(new Date());
        comment.setGiveCount(0);
        comment.setIsDeleted(0);

        // 处理 parentId 和 replycomId 逻辑
        if (comment.getParentId() != null) {
            CommentBean parentComment = commentDao.getById(comment.getParentId());
            if (parentComment == null || parentComment.getIsDeleted() == 1) {
                throw new IllegalArgumentException("父评论不存在或已被删除");
            }
            // 如果是回复评论，设置 replycomId
            if (comment.getReplycomId() == null) {
                comment.setReplycomId(parentComment.getUserId());
            }
        } else {
            // 一级评论，确保这些字段为 null
            comment.setParentId(null);
            comment.setReplycomId(null);
        }

        // 插入评论
        int result = commentDao.add(comment);
        if (result > 0) {
            // 评论成功后发送消息
            PostBean post = postService.get(comment.getPostId());
            messageService.sendCommentMessage(
                    post.getUserId(), // 帖子作者ID（接收者）
                    comment.getUserId(), // 评论用户ID（发送者）
                    comment.getPostId(),
                    comment.getId(),
                    comment.getCommentContent()
            );
            return comment;
        }else {
            throw new RuntimeException("评论添加失败");
        }
    }
//    @Override
//    public List<CommentBean> all(CommentBean comment) {
//        if (comment.getPostId() == null) {
//            throw new IllegalArgumentException("帖子ID不能为空");
//        }
//        // 这里需要调用 commentDao.all(comment.getPostId()) 而不是 commentDao.all(comment)
//        return commentDao.all(comment.getPostId());
//    }


    @Override
    public int del(Integer id) {
        // 验证评论是否存在
        CommentBean comment = commentDao.getById(id);
        if (comment == null) {
            throw new IllegalArgumentException("评论不存在");
        }
        return commentDao.del(id);
    }

    @Override
    public int countByPostId(CommentBean comment) {
        if (comment.getPostId() == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }
        // 这里需要调用 commentDao.countByPostId(comment.getPostId())
        return commentDao.countByPostId(comment.getPostId());
    }
    @Override
    public List<CommentBean> all(CommentBean comment) {
        if (comment.getPostId() == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }
        // 修复：直接传递postId到DAO层
        List<CommentBean> flatComments = commentDao.all(comment.getPostId());

        // 将平面结构转换为树形结构
        return buildCommentTree(flatComments);
    }

    // 增强的树形结构构建方法
    private List<CommentBean> buildCommentTree(List<CommentBean> flatComments) {
        Map<Integer, CommentBean> commentMap = new HashMap<>();
        List<CommentBean> rootComments = new ArrayList<>();

        // 首先将所有评论放入map中，并初始化replies列表
        for (CommentBean comment : flatComments) {
            comment.setReplies(new ArrayList<>()); // 初始化replies列表
            commentMap.put(comment.getId(), comment);
        }

        // 构建树形结构
        for (CommentBean comment : flatComments) {
            if (comment.getParentId() == null) {
                // 这是一级评论
                rootComments.add(comment);
            } else {
                // 这是子评论，找到父评论并添加到其replies列表中
                CommentBean parent = commentMap.get(comment.getParentId());
                if (parent != null && parent.getReplies() != null) {
                    parent.getReplies().add(comment);
                }
            }
        }

        return rootComments;
    }
}